package so.ruo.api;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.CookieStore;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.client.LaxRedirectStrategy;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;

/**
 * 登录认证
 * 
 * @author http://www.710.so
 * 
 */
public class BaseAuth implements Authentication {

	private Logger logger = Logger.getLogger(BaseAuth.class);

	private HttpClientContext context = null;
	private CloseableHttpClient httpclient = null;
	private CloseableHttpResponse response = null;
	private HttpHost targetHost = null;
	private HttpHost proxyHost = null;
	private CookieStore cookieStore = null;
	private Proxy proxy = null;
	private Header[] headers = null;
	private RequestConfig config = null;
	private Map<String, String> headMap = null;
	private String charset = "utf-8";
	private long contentLength = -1;
	private String returns = null;
	private LaxRedirectStrategy redirectStrategy = null;
	private String httpType = "POST";

	public BaseAuth() {
		if (redirectStrategy == null) {
			redirectStrategy = new LaxRedirectStrategy();
		}
		if (httpclient == null) {
			PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
			connManager.setMaxTotal(200);
			connManager.setDefaultMaxPerRoute(20);
			connManager.closeIdleConnections(120, TimeUnit.SECONDS);
			httpclient = HttpClients.custom().setRedirectStrategy(redirectStrategy).setConnectionManager(connManager).build();
		}
		if (cookieStore == null) {
			cookieStore = new BasicCookieStore();
		}
		if (context == null) {
			context = HttpClientContext.create();
			context.setCookieStore(cookieStore);
		}
	}

	@Override
	public String login(String host, String site, Map<String, String> postInfo) throws Exception {
		try {
			// System.out.println("host:" + host);
			// System.out.println("site:" + site);
			HttpPost httpPost = new HttpPost(site);
			if (proxy != null) {
				targetHost = new HttpHost(host, 80, "http"); // 设定目标站点
				proxyHost = new HttpHost(proxy.getIp(), proxy.getPort(), proxy.getType().name()); // 设置代理对象 ip/代理名称,端口
				config = RequestConfig.custom().setProxy(proxyHost).build();
				httpPost.setConfig(config);
			}
			// 提交参数列表
			List<NameValuePair> nvps = new ArrayList<NameValuePair>();
			Iterator<String> iterator = postInfo.keySet().iterator();
			String key = null;
			String value = null;
			while (iterator.hasNext()) {
				key = iterator.next();
				value = postInfo.get(key);
				nvps.add(new BasicNameValuePair(key, value));
			}
			if (headMap != null) {
				iterator = headMap.keySet().iterator();
				while (iterator.hasNext()) {
					key = iterator.next();
					value = headMap.get(key);
					httpPost.setHeader(key, value);
				}
			}
			httpPost.setEntity(new UrlEncodedFormEntity(nvps));

			if (proxy != null) {
				response = httpclient.execute(targetHost, httpPost, context);
			} else {
				response = httpclient.execute(httpPost, context);
			}

			int statusCode = response.getStatusLine().getStatusCode();
			if (statusCode == HttpStatus.SC_OK) {
				// 获取响应实体
				HttpEntity entity = response.getEntity();
				if (entity != null) {
					contentLength = entity.getContentLength();// 响应内容长度
					returns = EntityUtils.toString(entity, charset);// 响应内容
					EntityUtils.consume(entity);
				}
			} else if (statusCode == HttpStatus.SC_MOVED_TEMPORARILY || statusCode == HttpStatus.SC_MOVED_PERMANENTLY) {
				// 当前页面发生重定向了
				Header[] headers = response.getHeaders("Location");
				if (headers != null && headers.length > 0) {
					String redirectUrl = headers[0].getValue();
					logger.debug("重定向的URL:" + redirectUrl);
					redirectUrl = redirectUrl.replace(" ", "%20");
					Thread.sleep(3000);
					HttpGet httpget = new HttpGet(redirectUrl);
					response = httpclient.execute(httpget, context);
					EntityUtils.consume(response.getEntity());
				}
			}
			return returns;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			// httpclient.close();
		}
		return null;
	}

	public HttpClientContext getContext() {
		return context;
	}

	public void setContext(HttpClientContext context) {
		this.context = context;
	}

	public CloseableHttpClient getHttpclient() {
		return httpclient;
	}

	public void setHttpclient(CloseableHttpClient httpclient) {
		this.httpclient = httpclient;
	}

	public HttpHost getTargetHost() {
		return targetHost;
	}

	public void setTargetHost(HttpHost targetHost) {
		this.targetHost = targetHost;
	}

	public HttpHost getProxyHost() {
		return proxyHost;
	}

	public void setProxyHost(HttpHost proxyHost) {
		this.proxyHost = proxyHost;
	}

	public CookieStore getCookieStore() {
		return cookieStore;
	}

	public void setCookieStore(CookieStore cookieStore) {
		this.cookieStore = cookieStore;
	}

	public Proxy getProxy() {
		return proxy;
	}

	public void setProxy(Proxy proxy) {
		this.proxy = proxy;
	}

	public Header[] getHeaders() {
		return headers;
	}

	public void setHeaders(Header[] headers) {
		this.headers = headers;
	}

	public CloseableHttpResponse getResponse() {
		return response;
	}

	public void setResponse(CloseableHttpResponse response) {
		this.response = response;
	}

	public RequestConfig getConfig() {
		return config;
	}

	public void setConfig(RequestConfig config) {
		this.config = config;
	}

	public String getCharset() {
		return charset;
	}

	public void setCharset(String charset) {
		this.charset = charset;
	}

	public long getContentLength() {
		return contentLength;
	}

	public void setContentLength(long contentLength) {
		this.contentLength = contentLength;
	}

	public String getReturns() {
		return returns;
	}

	public void setReturns(String returns) {
		this.returns = returns;
	}

	public LaxRedirectStrategy getRedirectStrategy() {
		return redirectStrategy;
	}

	public void setRedirectStrategy(LaxRedirectStrategy redirectStrategy) {
		this.redirectStrategy = redirectStrategy;
	}

	public static void main(String[] args) {

		// 代理IP查询链接 http://www.kuaidaili.com/

		BaseAuth auth = new BaseAuth();
		// 网易
		// String host = "163.com";
		// String site = "http://reg.163.com/logins.jsp?type=1&url=http://news.163.com/";
		// User user = new User("kojiss1230", "kojiss1234560");
		// Map<String,String> postInfo=new HashMap<String, String>();
		// postInfo.put("username", user.getAccount());
		// postInfo.put("password", user.getPassword());

		// 新浪
		// String host = "weibo.cn";
		// String site = "http://login.sina.com.cn/sso/login.php?client=ssologin.js(v1.3.16)";
		// User user = new User("kojiss1230@sina.com", "kojiss12300");
		// Map<String, String> postInfo = new HashMap<String, String>();
		// postInfo.put("mobile", user.getAccount());
		// postInfo.put("password_2845", user.getPassword());

		// 搜狐
		String host = "sohu.com";
		// http://passport.sohu.com/sso/login.jsp?userid=mokiss1230%40sohu.com&password=482b83051fe928f25fbb08c45458adae&appid=1019&persistentcookie=0&isSLogin=1&s=1437990739881&b=7&w=1920&pwdtype=1&v=26
		// String site = "http://passport.sohu.com/user/login";
		String site = "http://passport.sohu.com/sso/login.jsp";
		User user = new User("kokiss1230@sohu.com", "kokiss12300");
		Map<String, String> postInfo = new HashMap<String, String>();
		postInfo.put("userid", user.getAccount());
		postInfo.put("password", user.getPassword());
		postInfo.put("appid", "1019");
		// postInfo.put("loginSuccessCallFunction", "postLoginSuccessCall");
		// postInfo.put("loginFailCallFunction", "postLoginFailCall");
		postInfo.put("pwdtype", "0");
		// postInfo.put("domain", "sohu.com");
		postInfo.put("s", "1437990739881");
		postInfo.put("b", "7");
		postInfo.put("w", "1920");
		postInfo.put("v", "26");
		postInfo.put("persistentcookie", "0");
		postInfo.put("isSLogin", "1");

		// 凤凰
		// String host = "jifen.ifeng.com/";
		// String site = "http://jifen.ifeng.com/index/login/?username=13859992151&password=163%40com&inpass=on";
		// User user = new User("13859992151", "163%40com");//
		// Map<String, String> postInfo = new HashMap<String, String>();
		// postInfo.put("username", user.getAccount());
		// postInfo.put("password", user.getPassword());
		// postInfo.put("inpass", "on");

		Proxy proxy = new Proxy("1.198.227.73", 9000, ProxyType.HTTP);
		auth.setProxy(proxy);
		// CookieStore cookieStore = null;
		try {
			auth.setProxy(null);
			String responseContent = auth.login(host, site, postInfo);
			System.out.println("登录:" + responseContent);
		} catch (Exception e) {
			e.printStackTrace();
		}
		String content = null;
		try {
			HttpTools tool = new HttpTools();
			content = tool.getRequest("http://news.sohu.com/20150728/n417677649.shtml");
			System.out.println(content);//
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
